package kyz.icom.healthfrags;

import java.util.ArrayList;
import kyz.icom.slidingmenu.adapter.CommunityFragment;
import kyz.icom.slidingmenu.adapter.FindPeopleFragment;
import kyz.icom.slidingmenu.adapter.HomeFragment;
import kyz.icom.slidingmenu.adapter.NavDrawerListAdapter;
import kyz.icom.slidingmenu.adapter.PagesFragment;
import kyz.icom.slidingmenu.adapter.PhotosFragment;
import kyz.icom.slidingmenu.model.NavDrawerItem;
import working_fragment_tabs.Allergy_Activity;
import working_fragment_tabs.Allergy_Fragment;
import working_fragment_tabs.Immunization_Fragment;
import working_fragment_tabs.Medication_Fragment;
import mainCustomListAdapter.PHRElement;
import mainCustomListAdapter.PHRElementAdapter;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.support.v4.widget.DrawerLayout;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;


public class MainApplicationEntryPoint extends FragmentActivity {
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;
	// Navigation drawer title
	private CharSequence mDrawerTitle;
	// used to store application title
	private CharSequence mTitle;
	// slide menu items
	private String[] navMenuTitles;
	private TypedArray navMenuIcons;
	private ArrayList<NavDrawerItem> navDrawerItems;
	private NavDrawerListAdapter adapter;


	//private static ListView listView1;
	public static PHRElement[] phr_data;



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_layout);


		mTitle = mDrawerTitle = getTitle();

		// load slide menu items
		navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

		// navigation drawer icons from resources
		navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
		navDrawerItems = new ArrayList<NavDrawerItem>();

		// adding navigation drawer items to array
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
		// Find People
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
		// Photos
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
		// Communities, Will add a counter here
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
		// Pages
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
		// What's hot, We  will add a counter here
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));


		// Recycle the typed array
		navMenuIcons.recycle();
		mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

		// setting the navigation drawer list adapter
		adapter = new NavDrawerListAdapter(getApplicationContext(),
				navDrawerItems);
		mDrawerList.setAdapter(adapter);

		// enabling action bar application icon and behaving it as toggle button
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);

		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, //navigation menu toggle icon
				R.string.app_name, // navigation drawer open - description for accessibility
				R.string.app_name // navigation drawer close - description for accessibility
				) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				// calling onPrepareOptionsMenu() to show action bar icons
				invalidateOptionsMenu();
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				// calling onPrepareOptionsMenu() to hide action bar icons
				invalidateOptionsMenu();
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

//		if (savedInstanceState == null) {
//			// on first time display view for first navigation drawer item
//			displayView(0);
//		}
	}


	/**
	 * Slide menu item click listener
	 * */
	public class SlideMenuClickListener implements
	ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// display view for selected nav drawer item
			displayView(position);
		}
	}

	/**
	 * Diplaying fragment view for selected nav drawer list item
	 * */
	private void displayView(int position) {
		// update the main content by replacing fragments
		FragmentActivity fragment = null;
		switch (position) {
		case 0:
			fragment = new HomeFragment();
			break;
		case 1:
			fragment = new FindPeopleFragment();
			break;
		case 2:
			fragment = new PhotosFragment();
			break;
		case 3:
			fragment = new CommunityFragment();
			break;
		case 4:
			fragment = new PagesFragment();
			break;
		case 5:
			fragment = new PagesFragment();
			break;

		default:
			break;
		}

		if (fragment != null) {
			//			FragmentManager fragmentManager = getSupportFragmentManager();
			//			fragmentManager.beginTransaction()
			//					.replace(R.id.details, fragment).commit();
			//			
			//			FragmentTransaction ft = getFragmentManager()
			//					.beginTransaction();
			//			ft.replace(R.id.details, details);
			//			ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
			//			ft.commit();

			// update selected item and title, then close the drawer
			mDrawerList.setItemChecked(position, true);
			mDrawerList.setSelection(position);
			setTitle(navMenuTitles[position]);
			mDrawerLayout.closeDrawer(mDrawerList);
		} else {
			// error in creating fragment
			Log.e("MainActivity", "Error in creating fragment");
		}
	}


	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}


	/**
	 * Creates action bar menu icons
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.actions, menu);
		return super.onCreateOptionsMenu(menu);
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		// toggle navigation drawer on selecting action bar application icon/title
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}

		switch (item.getItemId()) {
		case R.id.action_home:
			Intent intent = new Intent(this, MainApplicationEntryPoint.class);
			startActivity(intent);
			break;

		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * This is the "top-level" fragment, showing a list of items that the user
	 * can pick. Upon picking an item, it takes care of displaying the data to
	 * the user as appropriate based on the currrent UI layout.
	 */

	public static class TitlesFragment extends ListFragment {
		boolean mDualPane;
		int mCurCheckPosition = 0;

		// public static Weather[] weather_data;

		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);

			// Populate list with our static array of titles.
			// setListAdapter(new ArrayAdapter<String>(getActivity(),
			// android.R.layout.simple_list_item_activated_1,
			// Shakespeare.TITLES));

			phr_data = new PHRElement[] {
					new PHRElement(R.drawable.allergy, "Allergies"),
					new PHRElement(R.drawable.medications, "Medications"),
					new PHRElement(R.drawable.immunization,
							"Immunization Records"),
							new PHRElement(R.drawable.lab, "Lab Data"),
							new PHRElement(R.drawable.conditions, "Conditions"),
							new PHRElement(R.drawable.imaging, "Imaging"),
							new PHRElement(R.drawable.surgery, "Surgery"),
							new PHRElement(R.drawable.summary, "Summary") };

			setListAdapter(new PHRElementAdapter(getActivity(),
					R.layout.listview_item_row, phr_data));

			// Check to see if we have a frame in which to embed the details
			// fragment directly in the containing UI.
			View detailsFrame = getActivity().findViewById(R.id.details);
			mDualPane = detailsFrame != null
					&& detailsFrame.getVisibility() == View.VISIBLE;

			if (savedInstanceState != null) {
				// Restore last state for checked position.
				mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
			}

			if (mDualPane) {
				// In dual-pane mode, the list view highlights the selected
				// item.
				getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
				// Make sure our UI is in the correct state.
				showDetails(mCurCheckPosition);
			}
		}

		@Override
		public void onSaveInstanceState(Bundle outState) {
			super.onSaveInstanceState(outState);
			outState.putInt("curChoice", mCurCheckPosition);
		}

		@Override
		public void onListItemClick(ListView l, View v, int position, long id) {
			showDetails(position);
		}

		/**
		 * Helper function to show the details of a selected item, either by
		 * displaying a fragment in-place in the current UI, or starting a whole
		 * new activity in which it is displayed.
		 */
		void showDetails(int index) {
			mCurCheckPosition = index;
			back: if (mDualPane) {
				// We can display everything in-place with fragments, so update
				// the list to highlight the selected item and show the data.

				getListView().setItemChecked(index, true);

				// Check what fragment is currently shown, replace if needed.
				// Allergy_Fragment details = (Allergy_Fragment)
				// getFragmentManager()
				// .findFragmentById(R.id.details);
				// if (details == null ) {
				// back:
				if (index == 0) {

					Fragment details = (Fragment) TitlesFragment.this
							.getFragmentManager()
							.findFragmentById(R.id.details);
					// Make new fragment to show this selection.
					details = Allergy_Fragment.newInstance(index);

					// Execute a transaction, replacing any existing fragment
					// with this one inside the frame.
					FragmentTransaction ft = getFragmentManager()
							.beginTransaction();
					ft.replace(R.id.details, details);
					ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
					ft.commit();
					break back;
				}

				else if (index == 1) {

					// Fragment f1 = fm.findFragmentById(container1)

					Fragment details = (Fragment) getFragmentManager()
							.findFragmentById(R.id.details);
					// Make new fragment to show this selection.
					details = Medication_Fragment.newInstance(index);

					// Execute a transaction, replacing any existing fragment
					// with this one inside the frame.
					FragmentTransaction ft = getFragmentManager()
							.beginTransaction();
					ft.replace(R.id.details, details);
					ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
					ft.commit();

					break back;

				}

				else if (index == 2) {

					// Fragment f1 = fm.findFragmentById(container1)

					Fragment details = (Fragment) getFragmentManager()
							.findFragmentById(R.id.details);
					// Make new fragment to show this selection.
					details = Immunization_Fragment.newInstance(index);

					// Execute a transaction, replacing any existing fragment
					// with this one inside the frame.
					FragmentTransaction ft = getFragmentManager()
							.beginTransaction();
					ft.replace(R.id.details, details);
					ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
					ft.commit();

					break back;

				}

				else if (index == 3) {

					// Fragment f1 = fm.findFragmentById(container1)

					Fragment details = (Fragment) getFragmentManager()
							.findFragmentById(R.id.details);
					// Make new fragment to show this selection.
					details = Immunization_Fragment.newInstance(index);

					// Execute a transaction, replacing any existing fragment
					// with this one inside the frame.
					FragmentTransaction ft = getFragmentManager()
							.beginTransaction();
					ft.replace(R.id.details, details);
					ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
					ft.commit();

					break back;

				}

				else if (index == 4) {

					// Fragment f1 = fm.findFragmentById(container1)

					Fragment details = (Fragment) getFragmentManager()
							.findFragmentById(R.id.details);
					// Make new fragment to show this selection.
					details = Medication_Fragment.newInstance(index);

					// Execute a transaction, replacing any existing fragment
					// with this one inside the frame.
					FragmentTransaction ft = getFragmentManager()
							.beginTransaction();
					ft.replace(R.id.details, details);
					ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
					ft.commit();

					break back;

				}

				else if (index == 5) {

					// Fragment f1 = fm.findFragmentById(container1)

					Fragment details = (Fragment) getFragmentManager()
							.findFragmentById(R.id.details);
					// Make new fragment to show this selection.
					details = Medication_Fragment.newInstance(index);

					// Execute a transaction, replacing any existing fragment
					// with this one inside the frame.
					FragmentTransaction ft = getFragmentManager()
							.beginTransaction();
					ft.replace(R.id.details, details);
					ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
					ft.commit();

					break back;

				}

				else if (index == 6) {

					// Fragment f1 = fm.findFragmentById(container1)

					Fragment details = (Fragment) getFragmentManager()
							.findFragmentById(R.id.details);
					// Make new fragment to show this selection.
					details = Medication_Fragment.newInstance(index);

					// Execute a transaction, replacing any existing fragment
					// with this one inside the frame.
					FragmentTransaction ft = getFragmentManager()
							.beginTransaction();
					ft.replace(R.id.details, details);
					ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
					ft.commit();

					break back;

				}

				else if (index == 7) {

					// Fragment f1 = fm.findFragmentById(container1)

					Fragment details = (Fragment) getFragmentManager()
							.findFragmentById(R.id.details);
					// Make new fragment to show this selection.
					details = Medication_Fragment.newInstance(index);

					// Execute a transaction, replacing any existing fragment
					// with this one inside the frame.
					FragmentTransaction ft = getFragmentManager()
							.beginTransaction();
					ft.replace(R.id.details, details);
					ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
					ft.commit();

					break back;

				}

			} else {
				// Otherwise we need to launch a new activity to display
				// the dialog fragment with selected text.
				Intent intent = new Intent();
				intent.setClass(getActivity(), Allergy_Activity.class);
				intent.putExtra("index", index);
				startActivity(intent);
			}
		}
	}

}
